var WxParse = require('../../common/wxParse/wxParse.js');
var App = getApp();
Page({
  data: {
      detail: {},
      cartCount:0,
      reviews:{},
      specificationArray:[],
      indicatorDots: true,
      autoplay: false,
      interval: 3000,
      duration: 1000,
      tabs: ["商品详情",  "商品评价"],
      activeIndex: 0,
      num:1, // 商品数量
      minusStatuses: '',
      flag:0,
      firstIndex: -1,
      attrValueList: [],
  },
  onLoad (param) {
    let userId = wx.getStorageSync('userId')
    let agent = wx.getStorageSync('agent')
    if (param.package) {
      this.setData({package: 1})
    }
    this.setData({productId: param.id, buyerId: userId, agent}) // 商品id
    this.getProDetail(param.id)
  },
  getProDetail (id) { // 商品详情
    let {agent} = this.data
    App.HttpService.getProDetail({id: id, sellerId: agent.id}).then(res => {
      let data = res.data
      if (data.code == 200) {
        this.setData({detail: data.data})
        WxParse.wxParse('article', 'html', data.data.introduction, this, 5)
      }
    })
  },
  tabClick (e) {
    this.setData({
      activeIndex: e.currentTarget.id
    });
  },
  swiperchange () {},
  bindViewTap (e) {
    var param = e.currentTarget.dataset;
    var id = param["id"];
    var index=param["index"];
    this.setData({
      selected: id,
      firstIndex:index
    });
  },
  onCartClick (event) {
    wx.redirectTo({
      url: '../../cart/cart'
    })

  },
  setModalStatus (e) {
    // console.log("设置显示状态，1显示0不显示", e.currentTarget.dataset.status);
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export()
    })
    if (e.currentTarget.dataset.status == 1) {
      this.setData({
        showModalStatus: true
      });
    }
    var flag = e.currentTarget.dataset.flag ;
    this.setData({
      flag: flag
    });
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation
      })
      if (e.currentTarget.dataset.status == 0) {
        this.setData(
          {
            showModalStatus: false
          }
        );
      }
    }.bind(this), 100)
  },
  toMerchants () { // 去选店
    var cartCount = this.data.cartCount
    if (cartCount < 1) {
      wx.showToast({
        title: '请选择商品',
        image: '../../../assets/images/warning.png',
        duration: 1000
      })
      return
    }
    wx.navigateTo({
      url: '/pages/merchants/list/index?productStatus=0'
    })
  },
  addShopCart (e) { // 加入购物车 确定按钮
    let {productId, buyerId, num, detail, agent} = this.data
    var flag = this.data.flag
    if (flag == 0) {      
      App.HttpService.cartAdd({
        buyerId, productId, quantity: num, sellerId: agent.id
      }).then(res => {
        let data = res.data
        if (data.code == 200) {
          wx.showToast({
            title: '加入购物车成功',
            icon: 'success',
            duration: 1500
          })
          this.setData({cartCount: num})
          let products = [{
            id: detail.id,
            name: detail.name,
            image: detail.thumbnail,
            price: detail.price,
            num: num,
            unit: detail.specification + detail.unit
          }]
          wx.setStorageSync('products', products)
        } else {
          wx.showModal({
            showCancel: false,
            title: '错误',
            content: data.msg ? data.msg : "500"
          })
        }
      }) 
    } else if (flag == 1) {
      var itemsArray = new Array();
      var entity = new Object();
      entity.productId = productId;
      entity.pcount = quantity;
      entity.speci = speci;
      itemsArray.push(entity);
      console.log(JSON.stringify(itemsArray));
      wx.navigateTo({
        url: '../../pay/jiesuan?items=' + JSON.stringify(itemsArray)
      })
    }

    this.setData({
      showModalStatus: false
    });
  },
  bindMinus (e) { // 减少商品数量
    var num = this.data.num
    if (num > 1) { // 如果只有1件了，就不允许再减了
      num--
    }
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal'
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses
    minusStatuses = minusStatus
    this.setData({ // 将数值与状态写回
      num: num,
      minusStatuses: minusStatuses
    })
  },
  bindPlus (e) { // 增减商品数量
    var num = this.data.num
    num++ // 自增
    // 只有大于一件的时候，才能normal状态，否则disable状态
    var minusStatus = num <= 1 ? 'disabled' : 'normal'
    // 按钮可用状态
    var minusStatuses = this.data.minusStatuses
    minusStatuses = minusStatus
    this.setData({ // 将数值与状态写回
      num: num,
      minusStatuses: minusStatuses
    })
  },
  bindManual (e) {
    wx.showLoading({
      title: '操作中',
      mask: true
    });
    var num = parseInt(e.detail.value);
    // 将数值与状态写回
    this.setData({
      num: num
    });
    wx.hideLoading();
  },
  bindManualTapped () {
    // 什么都不做，只为打断跳转
  },
  distachAttrValue (detail) {
    // 将后台返回的数据组合成类似
    // {
    //   attrKey:'型号',
    //   attrValueList:['1','2','3']
    // }
    var attrValueList = this.data.attrValueList;
    var specificationArray = this.data.specificationArray;
    if (detail.specifications.length>0){
      for (var i = 0; i < detail.specifications.length; i++) {
        var attrKey = "";
        var attrKeyId = "";
        var attrValues = [];
        var attrValuesId = [];
        var attrValueStatus = [];
        attrKey = detail.specifications[i].specification.name;
        attrKeyId = detail.specifications[i].specification.id;
        specificationArray.push({
          sfId: '',
          spvId: ''
        });
        for (var j = 0; j < detail.specifications[i].specificationValues.length; j++) {
          attrValues.push(detail.specifications[i].specificationValues[j].name);
          attrValuesId.push(detail.specifications[i].specificationValues[j].id);
          attrValueStatus.push(true);
        }
        attrValueList.push({
          attrKey: attrKey,
          attrKeyId: attrKeyId,
          attrValues: attrValues,
          attrValuesId: attrValuesId,
          attrValueStatus: attrValueStatus
        });
      }
    }
    this.setData({
      attrValueList: attrValueList
    });
  },
  selectAttrValue (e) {
    // 点选属性值，联动判断其他属性值是否可选
    // {
    //   attrKey:'型号',
    //   attrValueList:['1','2','3'],
    //   selectedValue:'1',
    //   attrValueStatus:[true,true,true]
    // }
    // console.log(e.currentTarget.dataset);
    var attrValueList = this.data.attrValueList;
    var specificationArray = this.data.specificationArray;
    var index = e.currentTarget.dataset.index;//属性索引
    var key = e.currentTarget.dataset.key;
    var value = e.currentTarget.dataset.value;
    var sfId = e.currentTarget.dataset.sfid;
    var spvId = e.currentTarget.dataset.id;
    if (e.currentTarget.dataset.status || index == this.data.firstIndex) {
      this.selectValue(attrValueList, index, key, value);
      specificationArray[index].sfId=sfId;
      specificationArray[index].spvId=spvId;
      this.setData({
        specificationArray: specificationArray
      });
      console.log(this.data.specificationArray);
    }else{
      console.log("未进入");
    }
  },
  selectValue (attrValueList, index, key, value, unselectStatus) {
    // console.log('firstIndex', this.data.firstIndex);
    // 选中
    var includeGroup = [];
    if (index == this.data.firstIndex && !unselectStatus) { // 如果是第一个选中的属性值，则该属性所有值可选
      // 其他选中的属性值全都置空
      // console.log('其他选中的属性值全都置空', index, this.data.firstIndex, !unselectStatus);
      for (var i = 0; i < attrValueList.length; i++) {
        for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
          attrValueList[i].selectedValue = '';
        }
      }
    }
    attrValueList[index].selectedValue = value;
    this.setData({
      attrValueList: attrValueList
    });

    var count = 0;
    for (var i = 0; i < attrValueList.length; i++) {
      for (var j = 0; j < attrValueList[i].attrValues.length; j++) {
        if (attrValueList[i].selectedValue) {
          count++;
          break;
        }
      }
    }
    if (count < 2) {// 第一次选中，同属性的值都可选
      this.setData({
        firstIndex: index
      });
    } else {
      this.setData({
        firstIndex: -1
      });
    }
  }
 
})